/**
 *
 */
package com.et114.core.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;



import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;


import com.et114.components.acegi.Constants;
import com.et114.core.common.AppContext;
import com.et114.core.common.CONST;
import com.et114.core.common.Error;
import com.et114.core.control.TokenMapClient;
import com.et114.core.dao.vo.BaseVO;
import com.et114.core.exception.CheckException;
import com.et114.core.exception.ModuleException;
import com.et114.core.resources.FrameworkMessageManager;
import com.et114.core.utility.TokenMapUtils;
import com.et114.modules.org.utility.SessionUserInfo;
import com.et114.modules.products.commons.Const;

import net.sf.ehcache.CacheException;



/**
 * @author guanhw
 * TODO To change the template for this generated type comment go to Window -
 * Preferences - Java - Code Style - Code Templates
 */
/**
 *
 * XDoclet definition:
 *
 */
public class BaseDispatchAction extends DispatchAction {
	protected Log logger = LogFactory.getLog( this.getClass() );
	private final PathMatcher		pathMatcher								= new AntPathMatcher();
	protected Error error = new Error(); 
	/**
	 *
	 * @param beanname
	 * @return
	 */
	protected Object getBean( String beanname ) throws CheckException {
		return AppContext.getBean( beanname ) ;
	}

	/*
	 *
	 * @param request
	 * @param form
	 * @return
	 * @throws Exception

	protected Limit getLimit( HttpServletRequest request , com.et114.core.form.BaseActionForm form ) throws Exception {
		Context context = new HttpServletRequestContext( request );
		LimitFactory limitFactory = new TableLimitFactory( context , form.getTableId ( ) );
		return new TableLimit( limitFactory );
	}
	*/



	public final ActionForward execute( ActionMapping mapping, ActionForm form ,
			HttpServletRequest request , HttpServletResponse response ) throws Exception {
		long tic = System.currentTimeMillis ( ) ; 
		response.setHeader ( "Pragma" , "No-cache" );
		//response.setHeader( "Cache-Control", "public" );
		try {
			
			//init info 
			if ( AppContext.realPath == null ) {
				AppContext.realPath = request.getSession ( ).getServletContext ( ).getRealPath ( "/" ).trim ( ) ;
			}
			
			
			//令牌检查
			TokenMapClient client = ( TokenMapClient ) this.getBean (  "tokenMapClient" );
			boolean isTokenValid = false;
			if ( TokenMapUtils.isExistToken ( request , client , CONST.SAVE_TOKEN ) ) {
				saveToken ( request );
			}// 判断提交的action是否在保存token表中注册过，如果是，则保存token值，并将isSaved设为true

			if ( TokenMapUtils.isExistToken ( request , client , CONST.CHECK_TOKEN ) ) {
				isTokenValid = isTokenValid ( request );
				if ( !isTokenValid ) {
					Error error = new Error();
					error.setGoBack ( false ) ; 
					error.setErrorTitle ( FrameworkMessageManager.get ( ).getMessage ( "submit.resubmit" , request.getLocale ( ) ) ) ;
					request.setAttribute ( CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;
					return mapping.findForward( "glerror" ) ;
				}
			}
			if ( isTokenValid )	resetToken ( request );
			//结束令牌检查
			return super.execute( mapping, form, request, response );
		}
		catch ( java.lang.Throwable e ) {
			String goBackUrl = null;
			String em = null ;  
			if ( e instanceof CacheException ) {
				CacheException cacheEx = ( CacheException ) e;
				logger.error ( "Base CacheException::" + e.getMessage ( ) , cacheEx );
			} else if ( e instanceof CheckException ) {
				CheckException ce = ( CheckException ) e;
				goBackUrl = ce.getGoBackUrl ( );
				em = ce.getMessage ( ) ; 
				logger.error ( "CheckException::" + e.getMessage ( ) , ce );
			} else if ( e instanceof ModuleException ) { 
				ModuleException mex = ( ModuleException )  e ; 
				String bundle = mex.getBundle ( ) ; 
				logger.debug ( this.getClass ( ) + ".getBundle ( ):" + bundle ) ; 
				if ( bundle == null  )  bundle = Globals.MESSAGES_KEY ;
				Object [ ] object = ( ( ModuleException ) e ).getActionMessage ( ).getValues ( );
				String expkey = ( ( ModuleException ) e ).getActionMessage ( ).getKey ( );
			    em = getResources ( request , bundle ).getMessage ( expkey , object ) ; 
				logger.debug (  this.getClass ( ) + ".ModuleException:key:" + expkey + ".value:" + em ) ;
				goBackUrl = mex.getGoBackUrl ( ) ; 
				logger.error( "ModuleException::" + em , mex ) ;
			}
			else if ( e instanceof Exception ) {
				Exception ee = ( Exception ) e;
				//response.sendError ( response. SC_PAYMENT_REQUIRED  ) ;
				if ( !Constants.AUTH_ACCESSDENIED.equals ( ee.getMessage ( ) ) 
						&& ( ee.getMessage ( ) != null 
								&& !ee.getMessage ( ).startsWith ( Constants.SYS_EXP_K ) ) )
					logger.error( "Exception::" + ee.getMessage ( ) , ee ) ;
				else {
					em = ee.getMessage ( ) ;
					if ( em != null && em.startsWith ( Constants.AUTH_ACCESSDENIED ) )
						em = em.replaceAll ( Constants.AUTH_ACCESSDENIED , "" ) ; 
					if ( em != null && em.startsWith ( Constants.SYS_EXP_K ) ) 
						em = em.replaceAll ( Constants.SYS_EXP_K , "" ) ; 
					else
						logger.error( "ExceptionT::" + ee.getMessage ( ) , ee ) ;
				} 
			}
			else logger.error( "Error::" + e.getMessage ( ) , e ) ;
			
//判断
			String url = buildRequestUrl(  request.getServletPath ( ) ,
					request.getRequestURI ( ) , request.getContextPath ( ) ,
					request.getPathInfo ( ) , request.getQueryString ( ) ) ; 

			//

			String[] parrts = new String[] { "/**/*method*4View*"  } ;
			for ( int i = 0 ; i < parrts.length ; i ++ ) 
				if ( pathMatcher.match ( parrts[ i ] , url )  ) 
					return mapping.findForward ( "proerror" ) ; 
	

			
//			
			Error error = new Error();
			error.setErrorTitle ( em ) ;
			if ( goBackUrl != null && !"".equals ( goBackUrl.trim ( ) ) ) error.setGoBackUrl ( goBackUrl ) ;
			request.setAttribute (  CONST.VIEW_LAYER_EXCEPTION_KEY , error ) ;		
			
			return mapping.findForward( "glerror" ) ;
		}
		finally {
			logger.debug ( "count time..." + ( System.currentTimeMillis ( ) - tic ) ) ;
		}
	}

	/**
	 *
	 * @param request
	 * @return
	 */
	public SessionUserInfo getCurrentUser( HttpServletRequest request ) {
		HttpSession session = request.getSession ( );
		return  ( SessionUserInfo ) session .getAttribute ( Constants.SESSION_CURRENT_USER_KEY );
	}

	
	// TODO mv
	public void fillCrtUser ( HttpServletRequest request , BaseVO baseVO ) {
		Long userId = getCurrentUser ( request ).getUserId ( );
		baseVO.setCrtUser ( userId );
	}
	
	public void fillUpdtUser ( HttpServletRequest request , BaseVO baseVO ) {
		Long userId = getCurrentUser ( request ).getUserId ( );
		baseVO.setUpdtUser ( userId );
	}


	public String getSessionLanguage(  HttpServletRequest request ) {
		if ( request.getSession ( ).getAttribute ( Const.SESSION_LANGUAGE_KEY ) != null )
			return request.getSession ( ).getAttribute ( Const.SESSION_LANGUAGE_KEY ).toString ( ) ; 
		else return CONST.COUNTRY_ZH ;
	}

    public static String buildRequestUrl(String servletPath, String requestURI, String contextPath, String pathInfo,
            String queryString) {

            String uri = servletPath;

            if (uri == null) {
                uri = requestURI;
                uri = uri.substring(contextPath.length());
            }
            return uri + ((pathInfo == null) ? "" : pathInfo) + ((queryString == null) ? "" : ("?" + queryString));
        }
    
}
